package main

import (
	"encoding/base64"
	"flag"
	"log"
	"net/url"

	"gitee.com/dark.H/dark"
	"gitee.com/dark.H/darknet"
)

var (
	PAY = dark.Str(`POST /api/manage/data/es/dsl/query HTTP/1.1
	Host: sk-ml-uat-admin.seektop.vip
	Cookie: BubbleAppCookie=Zy%2F%2BoB8LRmoRVzlJDuftc2AAUbqLBrA%2Fv3tO8N%2FTQaDV1KnjAqU0%2FwJzU%2F3dAJbzYK98b33DAvnugyIBBpsLptVWculbN70EY9Vc0lxNiZGpGhIx6GCprzqAtLTRCv9N7c%2FHWgAGabW2Tkxj%2FZ99mukBEDYbwRoAY6MTluTT%2FFMFa489YMK6T6XEeMgvl2WA; admin-token=814f5886511d4d649f905153a12f8816; admin-uid=299
	Content-Length: 139
	Os_type: 0
	Opeartionmenu: %u6570%u636E%u7BA1%u7406-%u6E38%u620F%u6570%u636E-ES%u6570%u636E
	Sec-Ch-Ua: "Chromium";v="107", "Not=A?Brand";v="24"
	Some: header
	Uid: 299
	Sign: 07cd806ea67cdda125394858b3024f3a
	Sec-Ch-Ua-Platform: "macOS"
	Device_id: 1.0
	Sec-Ch-Ua-Mobile: ?0
	User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.5304.63 Safari/537.36
	Systemid: 55
	Content-Type: application/x-www-form-urlencoded
	Accept: application/json, text/plain, */*
	Timestamp: 1669889089000
	Gl_version: 2.0
	Token: 814f5886511d4d649f905153a12f8816
	Menuid: 10150002
	Version: 1.0
	Origin: https://sk-ml-uat-admin.seektop.vip
	Sec-Fetch-Site: same-origin
	Sec-Fetch-Mode: cors
	Sec-Fetch-Dest: empty
	Referer: https://sk-ml-uat-admin.seektop.vip/system/data-management/game-data
	Accept-Encoding: gzip, deflate
	Accept-Language: en-US,en;q=0.9
	Connection: close
	
	indices=report-rebate-2022&dsl=$ENCODE[url]{
		"size" : $${id},
		"query":{
			"match":{
						"index":"2022%2e01%2e01"
					}
		}
	}$ENCODEEND`)
)

func encode(pay string, encodeName ...string) string {
	name := "url"
	if encodeName != nil {
		name = encodeName[0]
	}
	switch name {
	case "base64":
		return base64.StdEncoding.EncodeToString([]byte(pay))
	default:
		return url.QueryEscape(pay)
	}
}

/*
包设置
PAY=`
/GET xxx.xxxx HTTTP 1.1
...
AUTH: Basic $${name_some}
...
`

参数设置 :
./pay -t http://xx.xxx.xx   name_some=sss
# 'name_some=sss' 会填充到包里面
*/

func main() {
	target := ""
	proxy := ""
	https := false
	flag.StringVar(&target, "t", "", "target ")
	flag.StringVar(&proxy, "socks5", "", "socks5 proxy")
	flag.BoolVar(&https, "https", false, "true to as https pay")

	flag.Parse()

	pays := dark.List[string](flag.Args()).Join(" ")
	kv := dark.Dict[dark.Str]{}
	pays.Split(",").Every(func(no int, i dark.Str) {
		kv = kv.Update(i.ParseKV())
	})
	if PAY.Find(`\$\${\w+}`).Len() > 0 && kv.Len() == 0 {
		dark.Str("must set parameter! ").Color("r").Println()
		PAY.Find(`(\$\${\w+})`).Every(func(no int, i dark.Str) {
			i.Color("g").Println("need set")
		})
		log.Fatal("")
	}
	pay := PAY.FormatDict(kv)
	encodes := pay.Extract("$ENCODE[", "$ENCODEEND")
	encodes.Every(func(no int, i dark.Str) {
		fs := i.Split("$ENCODE[", 2).Last().Split("]", 2)
		pay = pay.Replace(i.Str()+"$ENCODEEND", encode(fs[1].Str(), fs[0].Str()))
		// i.Color("y", "B").Println()
	})
	req := pay.AsNetReq()

	if target != "" {
		u, err := url.Parse(target)
		if err != nil {
			log.Fatal("is not url !", err)
		}

		req = req.SetHead(dark.Str("Host"), dark.Str(u.Host))
		if dark.Str(u.Scheme).StartsWith("https") {
			req.HTTPS = true
		}
		req = req.SetUri(dark.Str(u.RawPath))
	}
	req.HTTPS = https
	netreq := darknet.AsReq(req)

	if proxy != "" {
		netreq.Proxy = dark.Str(proxy)
	}
	req.Str.Color("B", "g").Add("\n\n ------sep--------\n").Print()
	// return
	netreq.Go().Print()

}
